<script setup>
import { ref } from "vue";
import * as XLSX from "xlsx";
defineProps({
  msg: String,
});

const fileList = ref([]);

const ExcelName = ref("");

/* 读取Excel文件数据 */
const readExcelFile = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: "array" });
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      resolve(jsonData);
    };
    reader.onerror = (e) => {
      reject(e);
    };
    reader.readAsArrayBuffer(file);
  });
};

/* 导出EXCEL */
const exportEXcel = (Excellist) => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new();

  const worksheet = XLSX.utils.aoa_to_sheet([...Excellist]);

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
  // 生成Excel文件
  XLSX.writeFile(workbook, `${ExcelName.value}合并.xlsx`);
};

/* 批量导出 */
let count = 0;
let allExcelList = [];
const allExport = async (list) => {
  if (count == list.length) {
    return allExcelList;
  }
  const file = list[count];
  try {
    const data = await readExcelFile(file);
    if (count > 0) {
      data.shift();
    }
    const newdata = [];
    data.forEach((item) => {
      if (item.length != 0) {
        newdata.push(item);
      }
    });
    allExcelList.push(newdata);
    count += 1;
    return allExport(list);
  } catch (error) {
    console.log(error);
    count += 1;
    ElMessage({
      message: "第" + count + "个文件读取失败",
      type: "error",
      plain: true,
    });
    return allExport(list);
  }
};

const clearFile = () => {
  ElMessage({
    message: "已清空文件列表",
    type: "success",
    plain: true,
  });
  fileList.value = [];
};

const loading = ref(false);
const submitUpload = async () => {
  count = 0;
  allExcelList = [];
  const newlist = fileList.value.map((item) => {
    return item.raw;
  });
  console.log(newlist);
  loading.value = true;
  const excellist = await allExport(newlist);
  const exportlist = excellist.flat(1);
  exportEXcel(exportlist);
  loading.value = false;
  ElNotification({
    title: "导出成功",
    message: `成功合并${exportlist.length}条数据`,
    type: "success",
    duration: 3000,
  });
};
</script>

<template>
  <div class="container" v-loading="loading" element-loading-text="数据处理中...">
    <div class="main_box">
      <h1>{{ msg }}</h1>
      <el-form
        style="max-width: 600px"
        status-icon
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="导出表名" prop="checkPass">
          <el-input
            v-model="ExcelName"
            placeholder="请输入导出的表名"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="pass">
          <el-upload
            v-model:file-list="fileList"
            action="#"
            :auto-upload="false"
            style="width: 100%"
            multiple="true"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div style="font-size: 12px; color: #666">
                <span v-if="fileList.length === 0"
                  >请选择需要导出的Excel文件,可批量选择</span
                >
                <span v-else>已选择{{ fileList.length }}个文件</span>
              </div>
            </template>
            <el-button
              style="margin-left: 20px"
              type="danger"
              @click="clearFile"
            >
              清空
            </el-button>
            <el-button
              style="margin-left: 20px"
              type="success"
              @click="submitUpload"
            >
              导出
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.container {
  width: 100%;
  display: flex;
  justify-content: center;
  .main_box {
    width: 600px;
  }
}
</style>
